package com.erp.dao.impl;

import com.erp.bean.OrderState;
import com.erp.dao.OrderStateDao;
import com.erp.util.db.DataBaseDao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lpy
 * 订单状态数据访问实现类
 */
public class OrderStateDaoImpl extends DataBaseDao implements OrderStateDao {
    @Override
    public int update(OrderState orderState) throws SQLException {
        //获取数据库连接对象
        buildConnection();
        String sql = "update orderstate set state=? where sid=?";
        //创建预编译指令对象
        pstmt = conn.prepareStatement(sql);
        //设置参数
        pstmt.setString(1,orderState.getState());
        pstmt.setInt(2,orderState.getSid());
        //执行更新操作并返回结果
        return pstmt.executeUpdate();
    }

    @Override
    public OrderState findById(Integer id) throws SQLException {
        //获取数据库连接对象
        buildConnection();
        OrderState orderState = null;
        String sql = "SELECT sid,state from orderstate where sid=?";
        //创建预编译对象
        pstmt = conn.prepareStatement(sql);
        //设置参数
        pstmt.setInt(1,id);
        //执行查询
        rs = pstmt.executeQuery();
        if (rs.next()){
            //创建订单状态对象 通过查询结果给对象赋值
            orderState = new OrderState(rs.getInt(1),rs.getString(2));
        }
        return orderState;
    }

    @Override
    public List<OrderState> findAll() throws SQLException {
        //获取数据库连接对象
        buildConnection();
        List<OrderState> orderStateList = new ArrayList<>();
        String sql = "SELECT sid,state FROM orderstate";
        //创建预编译对象
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            //创建订单状态对象
            OrderState orderState = new OrderState(rs.getInt(1),rs.getString(2));
            //将对象添加到集合中
            orderStateList.add(orderState);
        }
        return orderStateList;
    }
}
